<template>
	<view class="profile-edit-container">
		<!-- 主内容区 -->
		<scroll-view scroll-y class="content-wrapper" :show-scrollbar="false">
			<!-- 头像上传卡片 -->
			<view class="upload-card">
				<view class="card-header">
					<text class="card-title">头像设置</text>
					<text v-if="isAvatarLocked" class="status-tag warning">
						冷却中（剩余{{ avatarLockDays }}天）
					</text>
				</view>

				<view class="avatar-upload-wrapper">
					<u-avatar :src="form.avatar || defaultAvatar" size="80" mode="aspectFill" :borderWidth="4"
						borderColor="#fff" :shadow="2"></u-avatar>

					<u-upload ref="avatarUploader" :action="uploadConfig.avatar" :auto-upload="true" :max-count="1"
						:disabled="isAvatarLocked" :header="authHeaders" :form-data="{ type: 'avatar' }"
						:show-progress="false" @on-success="handleAvatarSuccess" custom-btn>
						<u-button size="mini" shape="circle" :disabled="isAvatarLocked" :custom-style="{
marginTop: '20rpx',
width: '180rpx',
backgroundColor: isAvatarLocked ? '#f5f5f5' : '#fff',
color: isAvatarLocked ? '#c0c4cc' : '#2979ff'
}">
							<u-icon name="camera-fill" size="16" :color="isAvatarLocked ? '#c0c4cc' : '#2979ff'"
								style="margin-right: 8rpx"></u-icon>
							{{ isAvatarLocked ? '不可修改' : '更换头像' }}
						</u-button>
					</u-upload>
				</view>
			</view>

			<!-- 视频上传卡片 -->
			<view class="upload-card">
				<view class="card-header">
					<text class="card-title">个人VCR</text>
					<text v-if="isVcrLocked" class="status-tag warning">
						冷却中（剩余{{ vcrLockDays }}天）
					</text>
				</view>

				<u-upload ref="vcrUploader" :action="uploadConfig.video" :file-list="vcrFileList" :max-count="1"
					:disabled="isVcrLocked" :header="authHeaders" :form-data="{ type: 'video' }" accept="video"
					@on-success="handleVcrSuccess" @on-remove="handleVcrRemove">
					<template v-slot:default>
						<view class="video-preview-wrapper" v-if="form.vcr">
							<video :src="form.vcr" controls class="video-player" :poster="vcrPoster"></video>
							<view class="video-actions">
								<u-icon name="close-circle-fill" size="24" color="#fff"
									@click="confirmRemoveVcr"></u-icon>
							</view>
						</view>

						<u-button v-else size="mini" shape="circle" :disabled="isVcrLocked" :custom-style="{
width: '220rpx',
backgroundColor: isVcrLocked ? '#f5f5f5' : '#fff',
color: isVcrLocked ? '#c0c4cc' : '#2979ff'
}">
							<u-icon name="video-fill" size="16" :color="isVcrLocked ? '#c0c4cc' : '#2979ff'"
								style="margin-right: 8rpx"></u-icon>
							{{ isVcrLocked ? '不可上传' : '上传介绍视频' }}
						</u-button>
					</template>
				</u-upload>
			</view>

			<!-- 相册上传卡片 -->
			<view class="upload-card">
				<view class="card-header">
					<text class="card-title">个人相册</text>
					<text class="photo-count">{{ form.gallery.length }}/9</text>
					<text v-if="isGalleryLocked" class="status-tag warning">
						冷却中（剩余{{ galleryLockDays }}天）
					</text>
				</view>

				<u-upload ref="galleryUploader" :action="uploadConfig.image" :file-list="galleryFileList" :max-count="9"
					:disabled="isGalleryLocked" :header="authHeaders" :form-data="{ type: 'gallery' }" multiple
					@on-success="handleGallerySuccess" @on-remove="handleGalleryRemove">
					<template v-slot:default>
						<view class="gallery-grid">
							<view v-for="(item, index) in form.gallery" :key="index" class="gallery-item">
								<image :src="item.url" mode="aspectFill" class="gallery-image"></image>
								<view class="image-overlay">
									<u-icon name="close-circle-fill" size="20" color="#fff"
										@click.stop="confirmRemoveImage(index)"></u-icon>
								</view>
							</view>

							<view v-if="form.gallery.length < 9 && !isGalleryLocked" class="add-item"
								@click="triggerGalleryUpload">
								<u-icon name="plus" size="32" color="#c0c4cc"></u-icon>
							</view>
						</view>
					</template>
				</u-upload>
			</view>

			<!-- 操作按钮区 -->
			<view class="action-area">
				<u-button type="primary" shape="circle" :loading="isSubmitting" :disabled="!hasChanges"
					@click="handleSubmit" :custom-style="{
height: '90rpx',
fontSize: '32rpx',
boxShadow: hasChanges ? '0 4rpx 12rpx rgba(57, 152, 255, 0.3)' : 'none'
}">
					{{ isSubmitting ? '保存中...' : '保存修改' }}
				</u-button>
			</view>
		</scroll-view>

		<!-- 删除确认弹窗 -->
		<u-modal v-model="showDeleteConfirm" :show-cancel-button="true" confirm-text="确认删除" cancel-text="再想想"
			@confirm="executeDelete">
			<view class="confirm-content">
				<text>确定要删除这个{{ deleteType === 'vcr' ? '视频' : '图片' }}吗？</text>
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					avatar: '',
					vcr: '',
					gallery: [],
					lastModified: {
						avatar: Date.now() - 15 * 86400 * 1000, // 模拟15天前修改
						vcr: 0,
						gallery: 0
					}
				},
				defaultAvatar: '/static/default-avatar.png',
				vcrPoster: '/static/video-poster.png',
				uploadConfig: {
					avatar: 'https://api.example.com/upload/avatar',
					video: 'https://api.example.com/upload/video',
					image: 'https://api.example.com/upload/image'
				},
				isSubmitting: false,
				showDeleteConfirm: false,
				deleteType: '',
				deleteIndex: null,
				originalData: {}
			}
		},
		computed: {
			authHeaders() {
				return {
					'Authorization': `Bearer ${uni.getStorageSync('token')}`,
					'X-Client-Type': 'mini-program'
				}
			},
			vcrFileList() {
				return this.form.vcr ? [{
					url: this.form.vcr
				}] : []
			},
			galleryFileList() {
				return this.form.gallery.map(item => ({
					url: item.url
				}))
			},
			isAvatarLocked() {
				const lockPeriod = 30 * 86400 * 1000
				return Date.now() - this.form.lastModified.avatar < lockPeriod
			},
			avatarLockDays() {
				const remain = this.form.lastModified.avatar + 30 * 86400 * 1000 - Date.now()
				return Math.ceil(remain / 86400 / 1000)
			},
			isVcrLocked() {
				const lockPeriod = 30 * 86400 * 1000
				return Date.now() - this.form.lastModified.vcr < lockPeriod
			},
			vcrLockDays() {
				const remain = this.form.lastModified.vcr + 30 * 86400 * 1000 - Date.now()
				return Math.ceil(remain / 86400 / 1000)
			},
			isGalleryLocked() {
				const lockPeriod = 30 * 86400 * 1000
				return Date.now() - this.form.lastModified.gallery < lockPeriod
			},
			galleryLockDays() {
				const remain = this.form.lastModified.gallery + 30 * 86400 * 1000 - Date.now()
				return Math.ceil(remain / 86400 / 1000)
			},
			hasChanges() {
				return JSON.stringify(this.form) !== JSON.stringify(this.originalData)
			}
		},
		methods: {
			// 初始化数据
			initData() {
				// 模拟从服务器加载数据
				this.originalData = {
					avatar: 'https://example.com/avatars/user123.jpg',
					vcr: 'https://example.com/videos/intro.mp4',
					gallery: [{
							url: 'https://example.com/gallery/1.jpg'
						},
						{
							url: 'https://example.com/gallery/2.jpg'
						}
					],
					lastModified: {
						avatar: Date.now() - 15 * 86400 * 1000,
						vcr: Date.now() - 10 * 86400 * 1000,
						gallery: Date.now() - 5 * 86400 * 1000
					}
				}

				// 深拷贝初始化表单数据
				this.form = JSON.parse(JSON.stringify(this.originalData))
			},

			// 头像上传成功
			handleAvatarSuccess(res) {
				if (res.code === 200) {
					this.form.avatar = res.data.url
					this.form.lastModified.avatar = Date.now()
					this.$u.toast(' 头像更新成功')
				} else {
					this.$refs.avatarUploader.clear()
					this.$u.toast(res.message || '头像上传失败')
				}
			},

			// 视频上传成功
			handleVcrSuccess(res) {
				if (res.code === 200) {
					this.form.vcr = res.data.url
					this.form.lastModified.vcr = Date.now()
					this.$u.toast(' 视频上传成功')
				} else {
					this.$refs.vcrUploader.clear()
					this.$u.toast(res.message || '视频上传失败')
				}
			},

			// 视频删除
			handleVcrRemove() {
				this.form.vcr = ''
			},

			// 确认删除视频
			confirmRemoveVcr() {
				this.deleteType = 'vcr'
				this.showDeleteConfirm = true
			},

			// 相册上传成功
			handleGallerySuccess(res) {
				if (res.code === 200) {
					this.form.gallery.push({
						url: res.data.url
					})
					this.form.lastModified.gallery = Date.now()
				} else {
					this.$refs.galleryUploader.remove(this.form.gallery.length)
					this.$u.toast(res.message || '图片上传失败')
				}
			},

			// 相册删除
			handleGalleryRemove(index) {
				this.form.gallery.splice(index, 1)
			},

			// 确认删除图片
			confirmRemoveImage(index) {
				this.deleteType = 'image'
				this.deleteIndex = index
				this.showDeleteConfirm = true
			},

			// 执行删除操作
			executeDelete() {
				if (this.deleteType === 'vcr') {
					this.$refs.vcrUploader.clear()
					this.form.vcr = ''
				} else {
					this.$refs.galleryUploader.remove(this.deleteIndex)
					this.form.gallery.splice(this.deleteIndex, 1)
				}
				this.showDeleteConfirm = false
			},

			// 触发相册上传
			triggerGalleryUpload() {
				this.$refs.galleryUploader.chooseFile()
			},

			// 提交表单
			async handleSubmit() {
				this.isSubmitting = true
				try {
					const res = await this.$u.api.updateProfile(this.form)
					if (res.code === 200) {
						this.originalData = JSON.parse(JSON.stringify(this.form))
						this.$u.toast(' 资料保存成功')
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						this.$u.toast(res.message || '保存失败')
					}
				} catch (error) {
					console.error(' 保存失败:', error)
					this.$u.toast(' 保存失败，请重试')
				} finally {
					this.isSubmitting = false
				}
			},

			// 返回处理
			handleBack() {
				if (this.hasChanges) {
					uni.showModal({
						title: '提示',
						content: '您有未保存的修改，确定要离开吗？',
						success: (res) => {
							if (res.confirm) uni.navigateBack()
						}
					})
				} else {
					uni.navigateBack()
				}
			}
		},

		onLoad() {
			this.initData()
		}
	}
</script>

<style lang="scss" scoped>
	.profile-edit-container {
		min-height: 100vh;
		background-color: #f8f9fa;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.content-wrapper {
			height: calc(100vh - var(--window-top));
			padding: 24rpx;
			box-sizing: border-box;
		}

		.upload-card {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 28rpx;
			margin-bottom: 24rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

			.card-header {
				display: flex;
				align-items: center;
				margin-bottom: 28rpx;

				.card-title {
					font-size: 32rpx;
					font-weight: 600;
					color: #333;
					margin-right: 16rpx;
				}

				.photo-count {
					font-size: 26rpx;
					color: #999;
					margin-right: auto;
				}

				.status-tag {
					font-size: 24rpx;
					padding: 4rpx 12rpx;
					border-radius: 20rpx;

					&.warning {
						background-color: #fff8e6;
						color: #f90;
					}
				}
			}
		}

		.avatar-upload-wrapper {
			display: flex;
			flex-direction: column;
			align-items: center;

			.u-avatar {
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
			}
		}

		.video-preview-wrapper {
			position: relative;
			width: 100%;
			height: 360rpx;
			border-radius: 12rpx;
			overflow: hidden;
			background-color: #000;
			margin-bottom: 20rpx;

			.video-player {
				width: 100%;
				height: 100%;
			}

			.video-actions {
				position: absolute;
				top: 16rpx;
				right: 16rpx;
				z-index: 2;

				.u-icon {
					background: rgba(0, 0, 0, 0.4);
					border-radius: 50%;
					padding: 6rpx;
				}
			}
		}

		.gallery-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 16rpx;

			.gallery-item,
			.add-item {
				position: relative;
				width: 100%;
				height: 0;
				padding-bottom: 100%;
				border-radius: 8rpx;
				overflow: hidden;
				background-color: #f5f5f5;

				.gallery-image {
					position: absolute;
					width: 100%;
					height: 100%;
					top: 0;
					left: 0;
				}

				.image-overlay {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					background: linear-gradient(to top, rgba(0, 0, 0, 0.3), transparent);
					display: flex;
					justify-content: flex-end;
					align-items: flex-start;
					padding: 12rpx;

					.u-icon {
						background: rgba(0, 0, 0, 0.4);
						border-radius: 50%;
						padding: 4rpx;
					}
				}
			}

			.add-item {
				display: flex;
				align-items: center;
				justify-content: center;
				border: 1rpx dashed #dcdfe6;
			}
		}

		.action-area {
			padding: 40rpx 0;

			.u-button {
				transition: all 0.3s;
			}
		}

		.confirm-content {
			padding: 32rpx;
			text-align: center;
			font-size: 30rpx;
			color: #333;
		}
	}
</style>